package cn.zhaoyuening.chat_server.handler;

import cn.zhaoyuening.chat_server.container.ChannelContainer;
import cn.zhaoyuening.chat_common.msg.BaseMsg;
import cn.zhaoyuening.chat_common.msg.ChatMsg;
import cn.zhaoyuening.chat_common.msg.PingMsg;
import cn.zhaoyuening.chat_common.msg.ResultMsg;
import cn.zhaoyuening.chat_server.utils.MsgHelper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;

/**
 * Created by Buynow on 2017/6/14.
 */
public class ChatServerHandler  extends SimpleChannelInboundHandler<BaseMsg> {

    public ChannelContainer container;

    public ChatServerHandler(ChannelContainer container) {
        this.container = container;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.id()+" connect the server!");
        container.add(channel);
    }



    @Override
    protected void messageReceived(ChannelHandlerContext ctx, BaseMsg msg) throws Exception {
        switch (msg.getType()) {
            case PING:
                ctx.writeAndFlush(new PingMsg());
                break;
            case CHAT:
                handleChat(ctx,(ChatMsg)msg);
                break;
            default:
                break;
        }
    }

    private void handleChat(ChannelHandlerContext ctx, ChatMsg msg) {
        if (msg.getUsername() == null) {
            ctx.writeAndFlush(ResultMsg.fail("username not null"));
            return ;
        }
        MsgHelper.sendToAllChannel(msg,container);
        System.out.println(msg.getContent());
    }



    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        container.remove(channel);
    }
}
